"""
从huada定时获取数据，并记录到我方sqlserver [huada]数据库中
"""
from config import Config
from plugin import SchedulerManager, Trigger, Mylogger, MyTime
from base import requests
from base import MY_STORED_CACHE, UPDATE_MY_STORED_CACHE
from module.huada.entity import *
# from http.client import HTTPConnection

# HTTPConnection.debuglevel = 1

# 全局配置
# url_huada = "https://jwebapi.genomics.cn/ehrapi_test/" if Config.config.env.development else "https://jwebapi.genomics.cn/ehrapi/"
url_huada = "https://jwebapi.genomics.cn/ehrapi/"
token_huada = None

do_test = Config.module_config.huada.do_test


@SchedulerManager.Scheduler(Trigger.interval(hours=1), delay=0)
def refresh_token():
    """ 定时获取华大token """
    get_token()
    # return token_huada


def get_token():
    """ 更新token """
    global token_huada
    url = url_huada + "accesstoken"
    data = {"agentId": "tunion", "appKey": "XD&Y%y^&NM.("}
    r = requests.post(url, json=data)
    result = r.json()
    if result.__contains__("errcode") and result["errcode"] == 200:
        token_huada = result["access_token"]
        Mylogger.info("获取华大token成功：" + token_huada)
    else:
        Mylogger.error("获取华大token失败")


def get_data_from_huada(sendcontent: dict, entityclass: BaseEntity, circle: int = 0):
    """ 获取华大数据 """
    time = None
    if circle == 0:
        if MY_STORED_CACHE.get(entityclass.table_name + '_get_time') is None:
            # MY_STORED_CACHE[entityclass.table_name + '_get_time'] = entityclass.get_time
            UPDATE_MY_STORED_CACHE(entityclass.table_name +
                                '_get_time', entityclass.get_time)

        if sendcontent.__contains__("begin") and sendcontent["begin"] == 0:
            sendcontent["begin"] = MY_STORED_CACHE[entityclass.table_name + '_get_time']
        elif sendcontent.__contains__("begin") and sendcontent["begin"] != 0:  # 获取指定时间段的数据
            sendcontent["begin"] = MyTime.timestr(MyTime.datetime_add(MY_STORED_CACHE[entityclass.table_name + '_get_time'], minutes=sendcontent["begin"]))

        time = MyTime.timestr()  # 记录获取数据的时间

        if sendcontent.__contains__("end") and sendcontent["end"] is None:
            sendcontent["end"] = time
    else:
        time = sendcontent["end"]  # 循环分页获取数据时，结束时间不应该更新

    url = url_huada + entityclass.url
    r = requests.post(url, json=sendcontent)
    result = r.json()
    if result.__contains__("code") and result["code"] == 200:
        datas = result["data"]
        if len(datas) > 0:
            for data in datas:
                entityclass.append(entityclass(**data))

        sendcontent["pageIndex"] += 1  # 页码+1
        get_data_from_huada(sendcontent, entityclass, 1)  # 递归获取数据
    elif result.__contains__("code") and result["code"] == 500:
        # Mylogger.error(f"get data from huada error [{result['msg']}]")
        if result["msg"] in ["token is invalid", "invalid token!"]:
            get_token()
        elif "数据为空" in result["msg"]:
            # save to db
            # time = MyTime.timestr()  # 记录获取完数据的时间
            entityclass.save_to_db()
            # MY_STORED_CACHE[entityclass.table_name + '_get_time'] = MyTime.timestr()
            UPDATE_MY_STORED_CACHE(entityclass.table_name + '_get_time', time)


def get_data(cls: BaseEntity, pagesize=100, pageindex=1):
    data = {"token": token_huada, "pageSize": pagesize,
            "pageIndex": pageindex, "begin": 0, "end": None}
    get_data_from_huada(data, cls)


############################################################################################################

# test
@SchedulerManager.Scheduler(Trigger.interval(minutes=3), delay=5)
def get_department_add(pageSize=1000, pageIndex=1):
    """ 获取华大部门增量信息 """
    get_data(O2Entity, pageSize)
    get_data(O3Entity, pageSize)
    get_data(O4Entity, pageSize)
    get_data(O5Entity, pageSize)
    get_data(O6Entity, pageSize)
    get_data(O7Entity, pageSize)


@SchedulerManager.Scheduler(Trigger.interval(minutes=5), delay=5)
def get_dhr_person_add(pageSize=1000, pageIndex=1):
    """ 获取华大人员增量信息 """
    data = {"token": token_huada, "pageSize": pageSize,
            "pageIndex": pageIndex, "begin": 0, "end": None}
    get_data_from_huada(data, PersonEntity)


@SchedulerManager.Scheduler(Trigger.cron(ss=0,mm=0,hh=1), delay=5)
def get_dhr_person_add_lastday(pageSize=1000, pageIndex=1):
    """ 获取华大人员前一天所有的增量信息 """
    data = {"token": token_huada, "pageSize": pageSize,
            "pageIndex": pageIndex, "begin": MyTime.timestrfrom(MyTime.timestamp()-86400), "end": None}
    get_data_from_huada(data, PersonEntity)


@SchedulerManager.Scheduler(Trigger.interval(minutes=3), delay=5)
def get_visitor_add(pageSize=1000, pageIndex=1):
    """ 获取外部人员增量信息 """
    data = {"token": token_huada, "pageSize": pageSize,
            "pageIndex": pageIndex, "begin": 0, "end": None}
    get_data_from_huada(data, VisitorEntity)


@SchedulerManager.Scheduler(Trigger.interval(minutes=5), delay=5)
def get_usercard_add(pageSize=1000, pageIndex=1):
    """ 获取华大人员卡片增量信息 """
    get_data(UserCardEntity, pageSize)


@SchedulerManager.Scheduler(Trigger.interval(minutes=3), delay=5)
def get_virtualcard_add(pageSize=1000, pageIndex=1):
    """ 获取虚拟卡片增量信息 """
    get_data(VirtualCardEntity, pageSize)


@SchedulerManager.Scheduler(Trigger.interval(minutes=3), delay=5)
def get_visitorcard_add(pageSize=1000, pageIndex=1):
    """ 获取外部人员卡片增量信息 """
    get_data(VisitorCardEntity, pageSize)


@SchedulerManager.Scheduler(Trigger.cron(hh='0/12', mm=0, ss=0), delay=5)
def get_city_add(pageSize=1000, pageIndex=1):
    """ 获取华大城市增量信息 """
    get_data(CityEntity, pageSize)


@SchedulerManager.Scheduler(Trigger.cron(hh='1/12', mm=0, ss=0), delay=5)
def get_company_add(pageSize=1000, pageIndex=1):
    """ 获取华大法人增量信息 """
    get_data(CompanyEntity, pageSize)


@SchedulerManager.Scheduler(Trigger.interval(minutes=3), delay=5)
def get_area_add(pageSize=1000, pageIndex=1):
    """ 获取华大区域增量信息 """
    get_data(AreaEntity, pageSize)


@SchedulerManager.Scheduler(Trigger.interval(minutes=3), delay=5)
def get_doors_add(pageSize=1000, pageIndex=1):
    """ 获取华大门禁增量信息 """
    get_data(DoorsEntity, pageSize)


@SchedulerManager.Scheduler(Trigger.interval(minutes=5), delay=5)
def get_doorsforbid_add(pageSize=10000, pageIndex=1):
    """ 获取华大门禁授权增量信息 """
    data = {
        "token": token_huada,
        "pageSize": pageSize,
        "pageIndex": pageIndex,
        "begin": -1,
        "end": None,
        "dataSysCode": Config.module_config.huada.system_code
    }
    get_data_from_huada(data, AuthEntity)


refresh_token()
get_department_add()
# get_area_add()
get_city_add()
get_company_add()
get_virtualcard_add()
get_dhr_person_add()
get_dhr_person_add_lastday()
get_visitor_add()
get_doors_add()
get_usercard_add()
get_visitorcard_add()
get_doorsforbid_add()


@SchedulerManager.Scheduler(Trigger.interval(minutes=10), delay=5)
def send_access_record():
    # 发送门禁记录
    data = {"token": token_huada, "data": ""}
    AccessRecordsEntity.get_data()
    AccessRecordsEntity.send_data(url_huada, data)


@SchedulerManager.Scheduler(Trigger.interval(minutes=10), delay=150)
def send_auth_result():
    # 发送门禁授权结果
    data = {"token": token_huada, "data": ""}
    AuthResultEntity.circ_check_data(url_huada, data)


# send_access_record()
# send_auth_result()
